package com.tiger.poker.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.tiger.poker.entity.Game21Vo;
import com.tiger.poker.util.Game21Util;
import com.tiger.poker.util.WebSocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

import static com.tiger.poker.util.GameUtil.*;


/**
 * The type Web socket.
 *
 * @author joy
 */
@Component
@ServerEndpoint("/webSocket21")
@Slf4j
public class WebSocket21 {

    private static final int MAX_PLAYER = 5;
    public static final String MESSAGE_SEPARATOR = "2sep1";

    private Session session;

    public static final Set<Game21Vo> GAME_21_VO_SET = Collections.synchronizedSet(new HashSet<>());

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        if (GAME_21_VO_SET.size() >= MAX_PLAYER) {
            WebSocketUtil.sendMessage(this.session, "游戏人满了,请稍后");
        }

    }

    @OnClose
    public void onClose() throws JsonProcessingException {

        Optional<Game21Vo> optionalVo = GAME_21_VO_SET.stream().filter(battleVO -> battleVO.getSession().equals(this.session)).findAny();
        if (optionalVo.isPresent()) {
            Game21Vo game21Vo = optionalVo.get();
            log.info("{},  离开了游戏", game21Vo.getName());
            GAME_21_VO_SET.remove(game21Vo);
            WebSocketUtil.sendMessageBatch21(GAME_21_VO_SET, SHOW_MESSAGE + MESSAGE_SEPARATOR + game21Vo.getName() + " 离开了游戏");
            WebSocketUtil.sendMessageBatch21(WebSocket21.GAME_21_VO_SET,
                    UPDATE_DATA + WebSocket21.MESSAGE_SEPARATOR + MAPPER.writeValueAsString(WebSocket21.GAME_21_VO_SET));
        }
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到客户端发来的消息：{}", message);

        String[] typeAndContents = message.split(MESSAGE_SEPARATOR);
        String type = typeAndContents[0];
        String content = typeAndContents[1];

        try {
            Game21Util.resolveMessage(Integer.parseInt(type), content, session);
        } catch (IOException e) {
            log.error(" resolve message error", e);
        }
    }


}
